<?php
/**
* EAjaxUpload class file.
* This extension is a wrapper of http://valums.com/ajax-upload/
*
* @author Vladimir Papaev <kosenka@gmail.com>
* @version 0.1
* @license http://www.opensource.org/licenses/bsd-license.php
*/

/**
How to use:

view:
$this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>'/controller/upload',
'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>10*1024*1024,// maximum file size in bytes
'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
//'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
//'messages'=>array(
//                  'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
//                  'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
//                  'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
//                  'emptyError'=>"{file} is empty, please select files again without it.",
//                  'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
//                 ),
//'showMessage'=>"js:function(message){ alert(message); }"
)
));

controller:

public function actionUpload()
{
Yii::import("ext.EAjaxUpload.qqFileUploader");

$folder='upload/';// folder for uploaded files
$allowedExtensions = array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
echo $result;// it's array
}

*/
class EAjaxUpload extends CWidget
{
    public $id="fileUploader";
    public $postParams=array();
    public $config=array();
    public $css=null;
    public $fileName='';
    public $location='';
    public $fieldName='';
    public $maxFile=0;
    public $deleteTitle='';
    public $displayFileName=false;
    
    public function checkDisplayFileName($name=''){
        return $this->displayFileName?"<span class='qq-upload-file'>".$name."</span>":"";
    }
    public function run()
    {    
        if(empty($this->config['action']))
        {
            throw new CException('EAjaxUpload: param "action" cannot be empty.');
        }

        if(empty($this->config['allowedExtensions']))
        {
            throw new CException('EAjaxUpload: param "allowedExtensions" cannot be empty.');
        }

        if(empty($this->config['sizeLimit']))
        {
            throw new CException('EAjaxUpload: param "sizeLimit" cannot be empty.');
        }

        unset($this->config['element']);

        echo '<div id="'.$this->id.'"><noscript><p>Please enable JavaScript to use file uploader.</p></noscript></div>';
        $assets = dirname(__FILE__).'/assets';
        $baseUrl = Yii::app()->assetManager->publish($assets,false,-1,true);
        //$baseUrl = Yii::app()->assetManager->publish($assets);

        Yii::app()->clientScript->registerScriptFile($baseUrl . '/fileuploader.js', CClientScript::POS_HEAD);

        $this->css=(!empty($this->css))?$this->css:$baseUrl.'/fileuploader.css';
        Yii::app()->clientScript->registerCssFile($this->css);

        $postParams = array('PHPSESSID'=>session_id(),'YII_CSRF_TOKEN'=>Yii::app()->request->csrfToken);
        if(isset($this->postParams))
        {
            $postParams = array_merge($postParams, $this->postParams);
        }
        $config = array(
        'element'=>'js:document.getElementById("'.$this->id.'")',
        'debug'=>false,
        'multiple'=>false
        );        
        $config = array_merge($config, $this->config);
        
        if($this->maxFile>0){
            $isfew=$this->maxFile>1?"s":"";
            $config['onSubmit'] ="js:function(id, fileName, responseJSON){
                                   if($('#".$this->id."').find('input[type=hidden]').length>=".$this->maxFile.")
                                    {                                                                                
                                        alert('Can not upload more than ".$this->maxFile." image".$isfew."!');
                                        return false;
                                    }
                                }";    
        }
        if($this->fileName && $this->location){
            $arrImages=explode(',',$this->fileName);
            $listImages='';
            $listHidden='';
            foreach($arrImages as $images){
                $listImages.="<li class=' qq-upload-success'>
                    ".$this->checkDisplayFileName($images)."
                    <img class='delete' src='/images/delete.png' />
                    <br/>
                    <img id='".$images."' class='images old' src='".$this->location.$images."' style='width:100px' />
                </li>";
                $listHidden.='<input class="load" type="hidden" name="'.$this->fieldName.'[]" value="'.$images.'" />';
            }  
            $html='<div class="qq-uploader"><div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>
            <div class="qq-upload-button">Chọn hình</div><ul class="qq-upload-list">'.$listImages.'</ul></div>'.$listHidden;
            
            $config["template"]=$html;            
        }
        
        
        $config['params']=$postParams;
        //CVarDumper::dump($this->config, 5, true) ;die;
        $config = CJavaScript::encode($config);
        
        Yii::app()->getClientScript()->registerScript("FileUploader_".$this->id, "var FileUploader_".$this->id." = new qq.FileUploader($config); ",CClientScript::POS_LOAD);

        $base=Yii::app()->request->baseUrl;
        $script=<<<EOD
        var location='{$this->location}';
        $("li.qq-upload-success img.delete").live('click',function(event, param1){                        
                var fileName=$(this).next().next().attr('id');           
                var _this=$(this);                
                $(this).attr('src','images/ajax-loader.gif');
                
                var data="SID=application.site.deleteFileInTemp&fileName="+fileName;
                if($(this).next().next().hasClass('old')){
                    data+="&location="+location;
                }
                
                $.ajax({  
                     type: 'POST',  
                     url: '{$base}/index.php?r=Core/service/ajax',  
                     data: data,  
                     async:false,                                      
                     success:function(json){
                        var result=eval(json);                        
                        _this.parents('div.qq-uploader').parent().find('input[value="'+fileName+'"]').remove();
                        //show button upload image
                        $('.qq-upload-button').show();
                        if(result.errors.length>0){
                            alert('Error when delete image!');
                        } 
                     }          
                 });  
                $(this).parent().remove();
            });
            
EOD;
                              
        Yii::app()->clientScript->registerScript("uploader_".$this->id,$script,CClientScript::POS_READY);
        

    }


}